#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

sem_t sem;

char ch[2] = {0};

void *fun1(void *arg)
{
	int i = 0;
	while(1)
	{
		sem_wait(&sem);
		if(i % 2 == 0)
		{
			ch[0] = 'a';
			sleep(1);
			ch[1] = 'b';
		}else
		{
			ch[0] = 'c';
			sleep(1);
			ch[1] = 'd';
		}
		sem_post(&sem);

		i = i + 1;
		if(i > 10000) i = 0;

	}
}

void *fun2(void *arg)
{
	while(1)
	{
		sem_wait(&sem);

		printf("ch[0] = %c,ch[1] = %c\n",ch[0],ch[1]);

		sem_post(&sem);

		sleep(1);
	}

}

int main()
{

	pthread_t tid1 = 0,tid2 = 0;
	int ret = 0;

	sem_init(&sem,0,1);

	ret = pthread_create(&tid1,NULL,fun1,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}

	ret = pthread_create(&tid2,NULL,fun2,NULL);
	if(ret != 0)
	{
		perror("pthread_create");
		exit(-1);
	}
	
	pthread_join(tid1,NULL);
	pthread_join(tid2,NULL);

	sem_destroy(&sem);

	return 0;

}





